<template>
  <div class="coupon-manage">
    <el-card>
      <div class="table-actions">
        <el-input v-model="search" placeholder="搜索优惠券名称/编号" style="width: 240px; margin-right: 12px;" clearable />
        <el-button type="primary" @click="openDialog('add')">新增优惠券</el-button>
      </div>
      
      <!-- 多条件搜索区域 -->
      <div class="search-panel">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="优惠券类型">
            <el-select v-model="searchForm.type" placeholder="全部类型" style="width: 140px;" clearable>
              <el-option label="满减券" value="满减券" />
              <el-option label="折扣券" value="折扣券" />
              <el-option label="包邮券" value="包邮券" />
              <el-option label="无门槛券" value="无门槛券" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" style="width: 120px;" clearable>
              <el-option label="草稿" value="草稿" />
              <el-option label="发布" value="发布" />
              <el-option label="作废" value="作废" />
            </el-select>
          </el-form-item>
          <el-form-item label="有效期类型">
            <el-select v-model="searchForm.validType" placeholder="全部" style="width: 140px;" clearable>
              <el-option label="固定" value="fixed" />
              <el-option label="领券当日生效" value="today" />
              <el-option label="次日生效" value="tomorrow" />
              <el-option label="限时" value="timed" />
            </el-select>
          </el-form-item>
          <el-form-item label="适用站点">
            <el-select v-model="searchForm.sites" placeholder="全部站点" style="width: 140px;" clearable>
              <el-option label="全站" value="all" />
              <el-option label="煤炉" value="mairo" />
              <el-option label="雅虎日拍" value="yahoo_auction" />
              <el-option label="雅虎闲置" value="yahoo_fleamarket" />
              <el-option label="bookoff" value="bookoff" />
            </el-select>
          </el-form-item>
          <el-form-item label="适用商品范围">
            <el-select v-model="searchForm.scope" placeholder="全部范围" style="width: 140px;" clearable>
              <el-option label="全场" value="all" />
              <el-option label="分类" value="category" />
              <el-option label="品牌" value="brand" />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button link @click="toggleAdvancedSearch">
              {{ showAdvancedSearch ? '收起' : '展开' }}高级搜索
              <el-icon style="margin-left: 4px;">
                <ArrowDown v-if="!showAdvancedSearch" />
                <ArrowUp v-else />
              </el-icon>
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 高级搜索区域 -->
        <div v-show="showAdvancedSearch" class="advanced-search">
          <el-form :inline="true" :model="advancedSearchForm" class="search-form">
            <el-form-item label="面值范围">
              <el-input-number v-model="advancedSearchForm.minAmount" placeholder="最小面值" style="width: 120px;" :min="0" />
              <span style="margin: 0 8px;">-</span>
              <el-input-number v-model="advancedSearchForm.maxAmount" placeholder="最大面值" style="width: 120px;" :min="0" />
            </el-form-item>
            <el-form-item label="发放类型">
              <el-select v-model="advancedSearchForm.grantType" placeholder="全部" style="width: 140px;" clearable>
                <el-option label="系统自动发放" value="system" />
                <el-option label="运营定向发放" value="targeted" />
              </el-select>
            </el-form-item>
            <el-form-item label="发放数量">
              <el-select v-model="advancedSearchForm.quantityType" placeholder="全部" style="width: 140px;" clearable>
                <el-option label="不限制" value="unlimited" />
                <el-option label="限制数量" value="limited" />
              </el-select>
            </el-form-item>
            <el-form-item label="已领取数量">
              <el-input-number v-model="advancedSearchForm.minClaimed" placeholder="最少领取" style="width: 120px;" :min="0" />
              <span style="margin: 0 8px;">-</span>
              <el-input-number v-model="advancedSearchForm.maxClaimed" placeholder="最多领取" style="width: 120px;" :min="0" />
            </el-form-item>
            <el-form-item label="客户标签">
              <el-select v-model="advancedSearchForm.customerTags" multiple placeholder="选择标签" style="width: 200px;" clearable>
                <el-option label="全部B端客户" value="b_all" />
                <el-option label="全部C端客户" value="c_all" />
                <el-option label="高消费" value="high_value" />
                <el-option label="重点客户" value="vip" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <el-table :data="pagedList" style="width: 100%; margin-bottom: 12px;">
        <el-table-column prop="id" label="编号" width="100" />
        <el-table-column prop="name" label="优惠券名称" width="150" />
        <el-table-column prop="description" label="优惠券简述" width="120" />
        <el-table-column prop="type" label="优惠券类型" width="100" />
        <el-table-column label="适用站点" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.sites.includes('all')" type="success" size="small">全站</el-tag>
            <div v-else>
              <el-tag v-for="site in scope.row.sites" :key="site" size="small" style="margin-right: 4px;">
                {{ getSiteName(site) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="面值" width="120">
          <template #default="scope">
            <span v-if="scope.row.type === '满减券'">{{ scope.row.amount }}日元</span>
            <span v-else-if="scope.row.type === '折扣券'">{{ scope.row.discountRate }}折</span>
            <span v-else-if="scope.row.type === '包邮券'">包邮</span>
            <span v-else-if="scope.row.type === '无门槛券'">{{ scope.row.amount }}日元</span>
          </template>
        </el-table-column>
        <el-table-column label="适用商品范围" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.scope.includes('all')" type="success" size="small">全场</el-tag>
            <div v-else>
              <el-tag v-for="item in scope.row.scope" :key="item" size="small" style="margin-right: 4px;">
                {{ getScopeName(item) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="邮寄方式" width="100">
          <template #default="scope">
            <span v-if="scope.row.type === '包邮券'">{{ getLogisticsName(scope.row.logistics) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="validDesc" label="有效期" width="150" />
        <el-table-column label="发布数量" width="100">
          <template #default="scope">
            <span v-if="scope.row.quantityType === 'unlimited'">不限制</span>
            <span v-else>{{ scope.row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已领取数量" width="100">
          <template #default="scope">
            {{ getClaimedCount(scope.row.id) }}
          </template>
        </el-table-column>
        <el-table-column label="发放信息" width="150">
          <template #default="scope">
            <div>
              <div style="margin-bottom: 4px;">
                <el-tag :type="scope.row.grantType === 'system' ? 'info' : 'warning'" size="small">
                  {{ scope.row.grantType === 'system' ? '系统发放' : '定向发放' }}
                </el-tag>
              </div>
              <div v-if="scope.row.grantType === 'targeted'">
                <div v-if="scope.row.customerTags === 'b_all'" style="color: #666; font-size: 12px;">
                  全部B端客户
                </div>
                <div v-else-if="scope.row.customerTags === 'c_all'" style="color: #666; font-size: 12px;">
                  全部C端客户
                </div>
                <div v-else-if="scope.row.customerTags === 'tags'" style="color: #666; font-size: 12px;">
                  客户标签: {{ scope.row.selectedTags?.length || 0 }}个
                </div>
                <div v-else-if="scope.row.customerTags === 'users' && scope.row.userIds" style="color: #666; font-size: 12px;">
                  <el-tooltip :content="scope.row.userIds" placement="top">
                    指定用户: {{ parseSelectedUsers(scope.row.userIds).length }}个
                  </el-tooltip>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="140" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="publishCoupon(scope.row)" :disabled="scope.row.status === '发布' || scope.row.status === '作废'">发布</el-button>
            <el-button size="small" @click="openDialog('edit', scope.row, scope.$index)" :disabled="scope.row.status === '作废'">编辑</el-button>
            <el-button size="small" type="danger" @click="cancelCoupon(scope.row)" :disabled="scope.row.status === '作废' || scope.row.status === '草稿'">作废</el-button>
            <el-button size="small" type="info" @click="viewOperationLog(scope.row)">操作记录</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="filteredList.length"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50]"
        style="margin-top: 12px; text-align: right;"
      />
      <el-dialog v-model="dialog.visible" :title="dialog.mode === 'add' ? '新增优惠券' : '编辑优惠券'" width="900px" :close-on-click-modal="false">
        <el-form :model="dialog.form" label-width="120px" ref="couponFormRef" :rules="formRules" class="coupon-form">
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="优惠券名称" prop="name">
                  <el-input v-model="dialog.form.name" placeholder="请输入优惠券名称" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item label="优惠券简述" prop="description">
                  <el-input v-model="dialog.form.description" maxlength="10" show-word-limit placeholder="请输入简述(限10字)" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="类型" prop="type">
                  <el-select v-model="dialog.form.type" style="width: 100%">
                    <el-option label="满减券" value="满减券" />
                    <el-option label="折扣券" value="折扣券" />
                    <el-option label="包邮券" value="包邮券" />
                    <el-option label="无门槛券" value="无门槛券" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 有效期配置 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Clock /></el-icon>
              <span>有效期配置</span>
            </div>
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item label="有效期类型" prop="validType">
                  <el-select v-model="dialog.form.validType" style="width: 100%">
                    <el-option label="固定" value="fixed" />
                    <el-option label="领券当日生效" value="today" />
                    <el-option label="次日生效" value="tomorrow" />
                    <el-option label="限时" value="timed" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <template v-if="dialog.form.validType === 'fixed'">
              <el-row :gutter="32">
                <el-col :span="12">
                  <el-form-item label="开始日期" prop="startTime">
                    <el-date-picker v-model="dialog.form.startTime" type="date" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束日期" prop="endTime">
                    <el-date-picker v-model="dialog.form.endTime" type="date" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-else-if="dialog.form.validType === 'today' || dialog.form.validType === 'tomorrow'">
              <el-row :gutter="32">
                <el-col :span="12">
                  <el-form-item label="有效天数" prop="validDays">
                    <el-input-number v-model="dialog.form.validDays" :min="1" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-else-if="dialog.form.validType === 'timed'">
              <el-row :gutter="32">
                <el-col :span="12">
                  <el-form-item label="有效分钟数" prop="validMinutes">
                    <el-input-number v-model="dialog.form.validMinutes" :min="1" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </div>

          <!-- 规则配置 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Setting /></el-icon>
              <span>规则配置</span>
            </div>
            <template v-if="dialog.form.type === '满减券'">
              <el-row :gutter="40">
                <el-col :span="12">
                  <el-form-item label="满额条件(日元)" prop="minAmount">
                    <el-input v-model="dialog.form.minAmount" placeholder="请输入门槛金额" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="减免金额(日元)" prop="amount">
                    <el-input v-model="dialog.form.amount" placeholder="请输入减免金额" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-else-if="dialog.form.type === '折扣券'">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="满额条件(日元)" prop="minAmount">
                    <el-input v-model="dialog.form.minAmount" placeholder="请输入门槛金额" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="折扣比例(%)" prop="discountRate">
                    <el-input v-model="dialog.form.discountRate" placeholder="请输入折扣比例" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="最高抵扣额" prop="maxDiscount">
                    <el-input v-model="dialog.form.maxDiscount" placeholder="请输入最高抵扣金额" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-else-if="dialog.form.type === '包邮券'">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="邮寄方式" prop="logistics">
                    <el-select v-model="dialog.form.logistics" style="width: 100%" placeholder="请选择邮寄方式">
                      <el-option label="日本邮政EMS" value="ems" />
                      <el-option label="DHL" value="sal" />
                      <el-option label="航空" value="air" />
                      <el-option label="海运" value="sea" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-else-if="dialog.form.type === '无门槛券'">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="减免金额(日元)" prop="amount">
                    <el-input v-model="dialog.form.amount" placeholder="请输入减免金额" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            
            <el-row :gutter="24" v-if="dialog.form.type !== '包邮券'">
              <el-col :span="12">
                <el-form-item label="适用站点" prop="sites">
                  <el-select v-model="dialog.form.sites" multiple style="width: 100%" @change="onSitesChange">
                    <el-option label="全站" value="all" :disabled="dialog.form.sites.length > 0 && dialog.form.sites[0] !== 'all'" />
                    <el-option label="煤炉" value="mairo" :disabled="dialog.form.sites.includes('all')" />
                    <el-option label="雅虎日拍" value="yahoo_auction" :disabled="dialog.form.sites.includes('all')" />
                    <el-option label="雅虎闲置" value="yahoo_fleamarket" :disabled="dialog.form.sites.includes('all')" />
                    <el-option label="bookoff" value="bookoff" :disabled="dialog.form.sites.includes('all')" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="适用商品范围" prop="scope">
                  <el-select v-model="dialog.form.scope" multiple style="width: 100%" @change="onScopeChange">
                    <el-option label="全场" value="all" :disabled="dialog.form.scope.length > 0 && dialog.form.scope[0] !== 'all'" />
                    <el-option label="分类" value="category" :disabled="dialog.form.scope.includes('all')" />
                    <el-option label="品牌" value="brand" :disabled="dialog.form.scope.includes('all')" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 分类选择 -->
            <template v-if="dialog.form.scope.includes('category')">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="选择分类">
                    <el-cascader
                      v-model="dialog.form.selectedCategories"
                      :options="categoryOptions"
                      :props="{ 
                        checkStrictly: true,
                        multiple: true,
                        emitPath: false
                      }"
                      multiple
                      style="width: 100%"
                      placeholder="请选择商品分类"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            
            <!-- 品牌选择 -->
            <template v-if="dialog.form.scope.includes('brand')">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="选择品牌">
                    <el-select v-model="dialog.form.selectedBrands" multiple style="width: 100%" placeholder="请选择品牌">
                      <el-option 
                        v-for="brand in brandOptions" 
                        :key="brand.value" 
                        :label="brand.label" 
                        :value="brand.value" 
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </div>

          <!-- 发放配置 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Bell /></el-icon>
              <span>发放配置</span>
            </div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="发放数量" prop="quantityType">
                  <el-radio-group v-model="dialog.form.quantityType">
                    <el-radio value="unlimited">不限制</el-radio>
                    <el-radio value="limited">
                      限制数量
                      <el-input-number 
                        v-if="dialog.form.quantityType === 'limited'" 
                        v-model="dialog.form.quantity" 
                        :min="1" 
                        style="margin-left: 8px; width: 100px" 
                        size="small"
                      />
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发放类型" prop="grantType">
                  <el-radio-group v-model="dialog.form.grantType">
                    <el-radio value="system">系统自动发放</el-radio>
                    <el-radio value="targeted">运营定向发放</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            
            <template v-if="dialog.form.grantType === 'targeted'">
              <el-row :gutter="24">
                <el-col :span="24">
                  <el-form-item label="客户标签" prop="customerTags">
                    <el-select v-model="dialog.form.customerTags" style="width: 100%" placeholder="请选择">
                      <el-option label="全部B端客户" value="b_all" />
                      <el-option label="全部C端客户" value="c_all" />
                      <el-option label="客户标签" value="tags" />
                      <el-option label="指定用户" value="users" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <!-- 客户标签多选 -->
              <template v-if="dialog.form.customerTags === 'tags'">
                <el-row :gutter="24">
                  <el-col :span="24">
                    <el-form-item label="选择客户标签" prop="selectedTags">
                      <el-select v-model="dialog.form.selectedTags" multiple style="width: 100%" placeholder="请选择客户标签">
                        <el-option label="高消费" value="high_value" />
                        <el-option label="重点客户" value="vip" />
                        <el-option label="新客户" value="new_customer" />
                        <el-option label="活跃客户" value="active_customer" />
                        <el-option label="流失客户" value="churned_customer" />
                        <el-option label="VIP客户" value="vip_customer" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
              
              <!-- 指定用户输入 -->
              <template v-if="dialog.form.customerTags === 'users'">
                <el-row :gutter="24">
                  <el-col :span="24">
                    <el-form-item label="指定用户" prop="userIds">
                      <el-input
                        v-model="dialog.form.userIds"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入用户ID，多个用户请用换行或逗号分隔"
                        style="width: 100%;"
                      />
                      <div class="form-tip">
                        <el-icon><InfoFilled /></el-icon>
                        <span>支持输入用户ID，多个用户请用换行或逗号分隔</span>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </template>
          </div>


        </el-form>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialog.visible = false">取消</el-button>
            <el-button type="primary" @click="saveCoupon" :loading="loading">
              {{ dialog.mode === 'add' ? '创建' : '更新' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
      
      <!-- 操作记录弹窗 -->
      <el-dialog v-model="operationLogDialog.visible" :title="`操作记录 - ${operationLogDialog.couponName}`" width="800px" :close-on-click-modal="false">
        <div class="operation-log-content">
          <div class="log-filter">
            <el-select v-model="operationLogDialog.filter.type" placeholder="操作类型" style="width: 150px; margin-right: 12px;" clearable>
              <el-option label="全部" value="" />
              <el-option label="创建" value="create" />
              <el-option label="编辑" value="edit" />
              <el-option label="发布" value="publish" />
              <el-option label="作废" value="cancel" />
              <el-option label="删除" value="delete" />
            </el-select>
            <el-date-picker
              v-model="operationLogDialog.filter.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 250px; margin-right: 12px;"
            />
            <el-button type="primary" @click="searchOperationLog">搜索</el-button>
            <el-button @click="resetOperationLogFilter">重置</el-button>
          </div>
          
          <el-table :data="operationLogDialog.list" style="width: 100%; margin-top: 16px;" border stripe>
            <el-table-column prop="timestamp" label="操作时间" width="160">
              <template #default="scope">
                {{ formatDateTime(scope.row.timestamp) }}
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="action" label="操作类型" width="100">
              <template #default="scope">
                <el-tag :type="getActionTagType(scope.row.action)" size="small">
                  {{ getActionText(scope.row.action) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="操作描述" />
            <el-table-column prop="ip" label="IP地址" width="120" />
            <el-table-column label="详情" width="80">
              <template #default="scope">
                <el-button size="small" link @click="viewOperationDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="operationLogDialog.page.current"
            v-model:page-size="operationLogDialog.page.size"
            :total="operationLogDialog.total"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50]"
            style="margin-top: 16px; text-align: right;"
            @current-change="loadOperationLog"
            @size-change="loadOperationLog"
          />
        </div>
        
        <!-- 操作详情弹窗 -->
        <el-dialog v-model="operationDetailDialog.visible" :title="`操作详情 - ${operationDetailDialog.title}`" width="600px" append-to-body>
          <div class="operation-detail">
            <div class="detail-item">
              <span class="label">操作时间：</span>
              <span>{{ formatDateTime(operationDetailDialog.data.timestamp) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">操作人：</span>
              <span>{{ operationDetailDialog.data.operator }}</span>
            </div>
            <div class="detail-item">
              <span class="label">操作类型：</span>
              <el-tag :type="getActionTagType(operationDetailDialog.data.action)" size="small">
                {{ getActionText(operationDetailDialog.data.action) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <span class="label">IP地址：</span>
              <span>{{ operationDetailDialog.data.ip }}</span>
            </div>
            <div class="detail-item">
              <span class="label">操作描述：</span>
              <span>{{ operationDetailDialog.data.description }}</span>
            </div>
            <div v-if="operationDetailDialog.data.changes && operationDetailDialog.data.changes.length > 0" class="detail-item">
              <span class="label">变更内容：</span>
              <div class="changes-list">
                <div v-for="change in operationDetailDialog.data.changes" :key="change.field" class="change-item">
                  <span class="field-name">{{ change.fieldName }}：</span>
                  <span class="old-value">{{ change.oldValue || '无' }}</span>
                  <span class="arrow">→</span>
                  <span class="new-value">{{ change.newValue || '无' }}</span>
                </div>
              </div>
            </div>
            <div v-if="operationDetailDialog.data.remark" class="detail-item">
              <span class="label">备注：</span>
              <span>{{ operationDetailDialog.data.remark }}</span>
            </div>
          </div>
        </el-dialog>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, ArrowUp, Document, Clock, Setting, Bell, InfoFilled } from '@element-plus/icons-vue'
import { useCouponStore } from '@/store/couponStore'

// 使用共享的优惠券存储
const couponStore = useCouponStore()

// 搜索表单数据
const searchForm = ref({
  type: '',
  status: '',
  validType: '',
  sites: '',
  scope: '',
  dateRange: []
})

// 高级搜索表单数据
const advancedSearchForm = ref({
  minAmount: null,
  maxAmount: null,
  grantType: '',
  quantityType: '',
  minClaimed: null,
  maxClaimed: null,
  customerTags: []
})

// 高级搜索显示状态
const showAdvancedSearch = ref(false)



// 操作记录相关接口
interface OperationLog {
  id: string
  couponId: string
  timestamp: string
  operator: string
  action: string
  description: string
  ip: string
  changes?: Array<{
    field: string
    fieldName: string
    oldValue: string
    newValue: string
  }>
  remark?: string
}

interface OperationDetailDialog {
  visible: boolean
  title: string
  data: OperationLog
}

interface OperationLogDialog {
  visible: boolean
  couponId: string
  couponName: string
  list: OperationLog[]
  total: number
  page: {
    current: number
    size: number
  }
  filter: {
    type: string
    dateRange: any[]
  }
}

interface CouponForm {
  id: string
  name: string
  description: string // 优惠券简述
  type: string
  amount: number
  minAmount: number
  discountRate?: number
  maxDiscount?: number
  validType: string
  startTime?: string
  endTime?: string
  validDays?: number
  validMinutes?: number
  logistics?: string
  status: string
  usageDesc: string
  quantityType: string
  quantity: number
  grantType: string
  customerTags: string
  selectedTags: string[]
  userIds: string
  sites: string[]
  scope: string[]
  validDesc?: string
  selectedCategories?: (string | number)[]
  selectedBrands?: (string | number)[]

  // 删除selectedProducts字段
  createdAt: string
}

// 使用共享存储的优惠券列表
const couponList = computed(() => couponStore.getAllCoupons())

// 在页面加载时同步数据到共享存储
onMounted(() => {
  // 同步初始数据到共享存储
  const initialData = [
    { id: '1004', name: '无门槛券', description: '无门槛减', type: '无门槛券', amount: 10, minAmount: 0, validType: 'tomorrow', validDays: 3, validDesc: '次日生效3天', status: '草稿', usageDesc: '', quantityType: 'limited', quantity: 50, grantType: 'targeted', customerTags: 'users', selectedTags: [], userIds: 'user001\nuser002\nuser003', sites: ['all'], scope: ['brand'], selectedCategories: [], selectedBrands: [1, 2], createdAt: '2024-06-04 16:45:00' },
    { id: '1003', name: '夏日折扣券', description: '夏季特惠', type: '折扣券', amount: 0, minAmount: 50, discountRate: 8.8, maxDiscount: 30, validType: 'timed', validMinutes: 120, validDesc: '领取后120分钟', status: '发布', usageDesc: '', quantityType: 'unlimited', quantity: 0, grantType: 'system', customerTags: '', selectedTags: [], userIds: '', sites: ['mairo', 'yahoo_auction'], scope: ['category'], selectedCategories: [1, 11], selectedBrands: [], createdAt: '2024-06-03 09:15:00' },
    { id: '1002', name: '全场包邮券', description: '全场包邮', type: '包邮券', amount: 0, minAmount: 0, validType: 'today', validDays: 7, validDesc: '领券当日生效7天', logistics: 'ems', status: '作废', usageDesc: '', quantityType: 'limited', quantity: 100, grantType: 'targeted', customerTags: 'b_all', selectedTags: [], userIds: '', sites: ['all'], scope: ['all'], selectedCategories: [], selectedBrands: [], createdAt: '2024-06-02 14:30:00' },
    { id: '1001', name: '新用户满减券', description: '新人专享', type: '满减券', amount: 20, minAmount: 100, validType: 'fixed', startTime: '2024-06-01', endTime: '2024-06-30', validDesc: '2024-06-01~2024-06-30', status: '发布', usageDesc: '新用户专享', quantityType: 'unlimited', quantity: 0, grantType: 'system', customerTags: '', selectedTags: [], userIds: '', sites: ['all'], scope: ['all'], selectedCategories: [], selectedBrands: [], createdAt: '2024-06-01 10:00:00' }
  ]
  
  // 添加您新创建的测试优惠券
  const testCoupon = {
    id: '1005',
    name: '测试',
    description: '测试',
    type: '满减券',
    amount: 200,
    minAmount: 1000,
    validType: 'fixed',
    startTime: '2024-12-19',
    endTime: '2024-12-31',
    validDesc: '2024-12-19~2024-12-31',
    status: '发布',
    usageDesc: '测试优惠券',
    quantityType: 'unlimited',
    quantity: 0,
    grantType: 'system',
    customerTags: '',
    selectedTags: [],
    userIds: '',
    sites: ['all'],
    scope: ['all'],
    selectedCategories: [],
    selectedBrands: [],

    createdAt: '2024-12-19 10:00:00'
  }
  
  initialData.unshift(testCoupon)
  couponStore.syncCouponList(initialData)
})

// 操作记录弹窗数据
const operationLogDialog = ref<OperationLogDialog>({
  visible: false,
  couponId: '',
  couponName: '',
  list: [],
  total: 0,
  page: {
    current: 1,
    size: 10
  },
  filter: {
    type: '',
    dateRange: []
  }
})

// 操作详情弹窗数据
const operationDetailDialog = ref<OperationDetailDialog>({
  visible: false,
  title: '',
  data: {
    id: '',
    couponId: '',
    timestamp: '',
    operator: '',
    action: '',
    description: '',
    ip: '',
    changes: [],
    remark: ''
  }
})

// 模拟操作记录数据
const operationLogsData = ref<Record<string, OperationLog[]>>({
  '1001': [
    {
      id: '1',
      couponId: '1001',
      timestamp: '2024-06-01 10:00:00',
      operator: '管理员',
      action: 'create',
      description: '创建优惠券',
      ip: '192.168.1.100',
      changes: [
        { field: 'name', fieldName: '优惠券名称', oldValue: '', newValue: '新用户满减券' },
        { field: 'type', fieldName: '类型', oldValue: '', newValue: '满减券' },
        { field: 'amount', fieldName: '面额', oldValue: '', newValue: '20日元' }
      ]
    },
    {
      id: '2',
      couponId: '1001',
      timestamp: '2024-06-01 14:30:00',
      operator: '运营专员',
      action: 'publish',
      description: '发布优惠券',
      ip: '192.168.1.101'
    },
    {
      id: '3',
      couponId: '1001',
      timestamp: '2024-06-02 09:15:00',
      operator: '管理员',
      action: 'edit',
      description: '修改优惠券信息',
      ip: '192.168.1.100',
      changes: [
        { field: 'amount', fieldName: '面额', oldValue: '20日元', newValue: '25日元' }
      ]
    }
  ],
  '1002': [
    {
      id: '4',
      couponId: '1002',
      timestamp: '2024-06-02 14:30:00',
      operator: '管理员',
      action: 'create',
      description: '创建包邮券',
      ip: '192.168.1.100',
      changes: [
        { field: 'name', fieldName: '优惠券名称', oldValue: '', newValue: '全场包邮券' },
        { field: 'type', fieldName: '类型', oldValue: '', newValue: '包邮券' },
        { field: 'logistics', fieldName: '邮寄方式', oldValue: '', newValue: '日本邮政EMS' }
      ]
    },
    {
      id: '5',
      couponId: '1002',
      timestamp: '2024-06-03 16:45:00',
      operator: '运营专员',
      action: 'cancel',
      description: '作废优惠券',
      ip: '192.168.1.102',
      remark: '活动结束，停止发放'
    }
  ]
})

// 已领取数量模拟数据
const claimedCounts = ref<Record<string, number>>({
  '1001': 45,
  '1002': 78,
  '1003': 23,
  '1004': 12,
  '1005': 89
})

const search = ref('')
const page = ref({ current: 1, size: 10 })
const filteredList = computed(() => {
  let result = couponList.value
  
  // 基础搜索（优惠券名称/编号）
  if (search.value) {
    result = result.filter(item => 
      item.name.includes(search.value) || 
      item.id.includes(search.value)
    )
  }
  
  // 多条件搜索
  if (searchForm.value.type) {
    result = result.filter(item => item.type === searchForm.value.type)
  }
  
  if (searchForm.value.status) {
    result = result.filter(item => item.status === searchForm.value.status)
  }
  
  if (searchForm.value.validType) {
    result = result.filter(item => item.validType === searchForm.value.validType)
  }
  
  if (searchForm.value.sites) {
    result = result.filter(item => 
      item.sites.includes(searchForm.value.sites) || 
      (searchForm.value.sites === 'all' && item.sites.includes('all'))
    )
  }
  
  if (searchForm.value.scope) {
    result = result.filter(item => 
      item.scope.includes(searchForm.value.scope) || 
      (searchForm.value.scope === 'all' && item.scope.includes('all'))
    )
  }
  

  
  // 创建时间范围搜索
  if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
    const startDate = new Date(searchForm.value.dateRange[0])
    const endDate = new Date(searchForm.value.dateRange[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(item => {
      const createDate = new Date(item.createdAt)
      return createDate >= startDate && createDate <= endDate
    })
  }
  
  // 高级搜索
  if (advancedSearchForm.value.minAmount !== null) {
    result = result.filter(item => item.amount >= (advancedSearchForm.value.minAmount || 0))
  }
  
  if (advancedSearchForm.value.maxAmount !== null) {
    result = result.filter(item => item.amount <= (advancedSearchForm.value.maxAmount || 0))
  }
  
  if (advancedSearchForm.value.grantType) {
    result = result.filter(item => item.grantType === advancedSearchForm.value.grantType)
  }
  
  if (advancedSearchForm.value.quantityType) {
    result = result.filter(item => item.quantityType === advancedSearchForm.value.quantityType)
  }
  
  if (advancedSearchForm.value.minClaimed !== null) {
    result = result.filter(item => getClaimedCount(item.id) >= (advancedSearchForm.value.minClaimed || 0))
  }
  
  if (advancedSearchForm.value.maxClaimed !== null) {
    result = result.filter(item => getClaimedCount(item.id) <= (advancedSearchForm.value.maxClaimed || 0))
  }
  
  if (advancedSearchForm.value.customerTags && advancedSearchForm.value.customerTags.length > 0) {
    result = result.filter(item => 
      item.customerTags.some(tag => advancedSearchForm.value.customerTags!.includes(tag))
    )
  }
  
  return result
})
const pagedList = computed(() => {
  const start = (page.value.current - 1) * page.value.size
  return filteredList.value.slice(start, start + page.value.size)
})
const couponFormRef = ref()
const dialog = ref({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: {
    id: '',
    name: '',
    description: '', // 初始化优惠券简述
    type: '满减券',
    amount: 0,
    minAmount: 0,
    discountRate: 0,
    maxDiscount: 0,
    validType: 'fixed',
    startTime: '',
    endTime: '',
    validDays: 0,
    validMinutes: 0,
    logistics: 'ems',
    status: '草稿',
    usageDesc: '',
    quantityType: 'unlimited',
    quantity: 0,
    grantType: 'system',
    customerTags: [],
    selectedUsers: '',
    sites: [],
    scope: [] as string[],
    selectedCategories: [],
    selectedBrands: [],
    // 删除selectedProducts字段
    createdAt: ''
  } as CouponForm,
  editIndex: -1
})

// 表单验证规则
const formRules = reactive({
  name: [
    { 
      required: true, 
      message: '请输入优惠券名称', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (!value || value.trim().length === 0) {
          callback(new Error('优惠券名称不能为空'))
        } else if (value.trim().length < 2 || value.trim().length > 50) {
          callback(new Error('长度在2到50个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  description: [
    { required: true, message: '请输入优惠券简述', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  validType: [
    { required: true, message: '请选择有效期类型', trigger: 'change' }
  ],
  startTime: [
    { 
      required: true, 
      message: '请选择开始日期', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.validType === 'fixed' && !value) {
          callback(new Error('请选择开始日期'))
        } else {
          callback()
        }
      }
    }
  ],
  endTime: [
    { 
      required: true, 
      message: '请选择结束日期', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.validType === 'fixed' && !value) {
          callback(new Error('请选择结束日期'))
        } else {
          callback()
        }
      }
    }
  ],
  validDays: [
    { 
      required: true, 
      message: '请输入有效天数', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (['today', 'tomorrow'].includes(dialog.value.form.validType) && (!value || value <= 0)) {
          callback(new Error('请输入有效天数'))
        } else {
          callback()
        }
      }
    }
  ],
  validMinutes: [
    { 
      required: true, 
      message: '请输入有效分钟数', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.validType === 'timed' && (!value || value <= 0)) {
          callback(new Error('请输入有效分钟数'))
        } else {
          callback()
        }
      }
    }
  ],
  minAmount: [
    { 
      required: true, 
      message: '请输入满额条件', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (['满减券', '折扣券'].includes(dialog.value.form.type) && (!value || value < 0)) {
          callback(new Error('请输入满额条件'))
        } else {
          callback()
        }
      }
    }
  ],
  amount: [
    { 
      required: true, 
      message: '请输入减免金额', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (['满减券', '无门槛券'].includes(dialog.value.form.type)) {
          if (!value) {
            callback(new Error('请输入减免金额'))
          } else if (isNaN(value)) {
            callback(new Error('请输入有效数字'))
          } else if (value <= 0) {
            callback(new Error('减免金额必须大于0'))
          } else if (value > 10000) {
            callback(new Error('减免金额不能超过10000日元'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ],
  discountRate: [
    { 
      required: true, 
      message: '请输入折扣比例', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.type === '折扣券' && (!value || value <= 0 || value >= 10)) {
          callback(new Error('请输入有效的折扣比例(0-10之间)'))
        } else {
          callback()
        }
      }
    }
  ],
  maxDiscount: [
    { 
      required: true, 
      message: '请输入最高抵扣额', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.type === '折扣券' && (!value || value <= 0)) {
          callback(new Error('请输入最高抵扣额'))
        } else {
          callback()
        }
      }
    }
  ],
  logistics: [
    { 
      required: true, 
      message: '请选择邮寄方式', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.type === '包邮券' && !value) {
          callback(new Error('请选择邮寄方式'))
        } else {
          callback()
        }
      }
    }
  ],
  sites: [
    { 
      required: true, 
      message: '请选择适用站点', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.type === '包邮券') {
          callback()
        } else if (!value || value.length === 0) {
          callback(new Error('请选择适用站点'))
        } else {
          callback()
        }
      }
    }
  ],
  scope: [
    { 
      required: true, 
      message: '请选择适用商品范围', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.type === '包邮券') {
          callback()
        } else if (!value || value.length === 0) {
          callback(new Error('请选择适用商品范围'))
        } else {
          callback()
        }
      }
    }
  ],
  quantity: [
    { 
      required: true, 
      message: '请输入发放数量', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.quantityType === 'limited' && (!value || value <= 0)) {
          callback(new Error('请输入发放数量'))
        } else {
          callback()
        }
      }
    }
  ],
  grantType: [
    { required: true, message: '请选择发放类型', trigger: 'change' }
  ],
  customerTags: [
    { 
      required: true, 
      message: '请选择客户标签', 
      trigger: 'change',
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.grantType === 'targeted' && (!value || value.length === 0)) {
          callback(new Error('请选择客户标签'))
        } else {
          callback()
        }
      }
    }
  ],
  selectedUsers: [
    {
      validator: (rule: any, value: any, callback: (err?: Error) => void) => {
        if (dialog.value.form.grantType === 'targeted' && value) {
          const userIds = parseSelectedUsers(value)
          const validation = validateUserIds(userIds)
          if (!validation.valid) {
            callback(new Error(validation.message))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

function openDialog(mode: 'add' | 'edit', row?: CouponForm, idx?: number) {
  dialog.value.mode = mode
  if (mode === 'add') {
    dialog.value.form = {
      id: '',
      name: '',
      description: '',
      type: '满减券',
      amount: 0,
      minAmount: 0,
      discountRate: 0,
      maxDiscount: 0,
      validType: 'fixed',
      startTime: '',
      endTime: '',
      validDays: 0,
      validMinutes: 0,
      logistics: 'ems',
      status: '草稿',
      usageDesc: '',
      quantityType: 'unlimited',
      quantity: 0,
      grantType: 'system',
      customerTags: '',
      selectedTags: [],
      userIds: '',
      sites: [],
      scope: [] as string[],
      selectedCategories: [],
      selectedBrands: [],

      // 删除selectedProducts字段
      createdAt: new Date().toISOString().slice(0, 19).replace('T', ' ')
    }
    dialog.value.editIndex = -1
  } else if (row && typeof idx === 'number') {
    dialog.value.form = { ...row }
    dialog.value.editIndex = idx
  }
  dialog.value.visible = true
}

function getValidTypeText(validType: string) {
  const typeMap: Record<string, string> = {
    'fixed': '固定',
    'today': '领券当日生效',
    'tomorrow': '次日生效',
    'timed': '限时'
  }
  return typeMap[validType] || validType
}

// 解析指定用户ID
function parseSelectedUsers(usersText: string): string[] {
  if (!usersText) return []
  return usersText.split(/[\n,，]/).map(id => id.trim()).filter(id => id)
}

// 验证用户ID格式
function validateUserIds(userIds: string[]): { valid: boolean; message?: string } {
  if (userIds.length === 0) {
    return { valid: false, message: '请输入至少一个用户ID' }
  }
  
  const invalidIds = userIds.filter(id => !/^[a-zA-Z0-9_-]+$/.test(id))
  if (invalidIds.length > 0) {
    return { valid: false, message: '用户ID只能包含字母、数字、下划线和连字符' }
  }
  
  return { valid: true }
}

async function saveCoupon() {
  // 先进行表单验证
  try {
    await couponFormRef.value.validate()
  } catch (error) {
    ElMessage.error({
      message: '表单验证失败，请检查所有必填项',
      duration: 3000,
      showClose: true
    })
    return
  }

  loading.value = true
  const idx = dialog.value.editIndex
  let validDesc = ''
  

  if (dialog.value.form.validType === 'fixed') {
    // 将日期格式化为当天的开始和结束时间
    const startDate = dialog.value.form.startTime ? new Date(dialog.value.form.startTime) : null
    const endDate = dialog.value.form.endTime ? new Date(dialog.value.form.endTime) : null
    
    const formatDate = (date: Date) => {
      return date.toISOString().split('T')[0] // 只保留日期部分 YYYY-MM-DD
    }
    
    validDesc = `${startDate ? formatDate(startDate) : ''}~${endDate ? formatDate(endDate) : ''}`
  } else if (dialog.value.form.validType === 'today') {
    validDesc = `领券当日生效${dialog.value.form.validDays}天`
  } else if (dialog.value.form.validType === 'tomorrow') {
    validDesc = `次日生效${dialog.value.form.validDays}天`
  } else if (dialog.value.form.validType === 'timed') {
    validDesc = `领取后${dialog.value.form.validMinutes}分钟`
  }
  
  const couponData = { ...dialog.value.form, validDesc }
  
  if (dialog.value.mode === 'add') {
    // 使用共享存储添加优惠券
    const newCoupon = couponStore.addCoupon(couponData)
    
    // 立即同步数据到共享存储，确保领券中心能看到新优惠券
    const currentList = couponStore.getAllCoupons()
    couponStore.syncCouponList([newCoupon, ...currentList])
    
    recordOperation(newCoupon.id, 'create', '创建优惠券', [
      { field: 'name', fieldName: '优惠券名称', oldValue: '', newValue: couponData.name },
      { field: 'type', fieldName: '类型', oldValue: '', newValue: couponData.type }
    ])
  } else if (idx > -1) {
    const oldData = couponList.value[idx]
    const changes = []
    
    // 比较变更内容
    if (oldData.name !== couponData.name) {
      changes.push({ field: 'name', fieldName: '优惠券名称', oldValue: oldData.name, newValue: couponData.name })
    }
    if (oldData.type !== couponData.type) {
      changes.push({ field: 'name', fieldName: '类型', oldValue: oldData.type, newValue: couponData.type })
    }
    if (oldData.amount !== couponData.amount) {
      changes.push({ field: 'amount', fieldName: '面额', oldValue: oldData.amount.toString(), newValue: couponData.amount.toString() })
    }
    
    // 使用共享存储更新优惠券
    couponStore.updateCoupon(couponData.id, couponData)
    if (changes.length > 0) {
      recordOperation(couponData.id, 'edit', '编辑优惠券', changes)
    }
  }
  loading.value = false
  dialog.value.visible = false
}

// 获取站点名称
function getSiteName(site: string): string {
  const siteMap: Record<string, string> = {
    'all': '全站',
    'mairo': '煤炉',
    'yahoo_auction': '雅虎日拍',
    'yahoo_fleamarket': '雅虎闲置',
    'bookoff': 'bookoff'
  }
  return siteMap[site] || site
}

// 获取商品范围名称
function getScopeName(scope: string): string {
  const scopeMap: Record<string, string> = {
    'all': '全场',
    'category': '分类',
    'brand': '品牌'
  }
  return scopeMap[scope] || scope
}

// 获取物流方式名称
function getLogisticsName(logistics: string): string {
  const logisticsMap: Record<string, string> = {
    'ems': '日本邮政EMS',
    'sal': 'DHL',
    'air': '航空',
    'sea': '海运'
  }
  return logisticsMap[logistics] || logistics
}

// 获取已领取数量
function getClaimedCount(couponId: string): number {
  return claimedCounts.value[couponId] || 0
}

// 发布优惠券
function publishCoupon(coupon: CouponForm) {
  couponStore.publishCoupon(coupon.id)
  
  // 发布后立即同步数据，确保领券中心能看到状态变更
  const currentList = couponStore.getAllCoupons()
  couponStore.syncCouponList([...currentList])
  
  recordOperation(coupon.id, 'publish', '发布优惠券')
  ElMessage.success('优惠券发布成功')
}

// 作废优惠券
function cancelCoupon(coupon: CouponForm) {
  ElMessageBox.confirm('确定要作废该优惠券吗？', '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    couponStore.cancelCoupon(coupon.id)
    recordOperation(coupon.id, 'cancel', '作废优惠券', [], '用户主动作废')
    ElMessage.success('优惠券已作废')
  }).catch(() => {
    // 用户取消操作
  })
}

// 查看操作记录
function viewOperationLog(coupon: CouponForm) {
  operationLogDialog.value.couponId = coupon.id
  operationLogDialog.value.couponName = coupon.name
  operationLogDialog.value.visible = true
  loadOperationLog()
}

// 加载操作记录
function loadOperationLog() {
  const logs = operationLogsData.value[operationLogDialog.value.couponId] || []
  let filteredLogs = [...logs]
  
  // 按操作类型过滤
  if (operationLogDialog.value.filter.type) {
    filteredLogs = filteredLogs.filter(log => log.action === operationLogDialog.value.filter.type)
  }
  
  // 按日期范围过滤
  if (operationLogDialog.value.filter.dateRange && operationLogDialog.value.filter.dateRange.length === 2) {
    const startDate = new Date(operationLogDialog.value.filter.dateRange[0])
    const endDate = new Date(operationLogDialog.value.filter.dateRange[1])
    endDate.setHours(23, 59, 59, 999)
    
    filteredLogs = filteredLogs.filter(log => {
      const logDate = new Date(log.timestamp)
      return logDate >= startDate && logDate <= endDate
    })
  }
  
  // 分页
  const start = (operationLogDialog.value.page.current - 1) * operationLogDialog.value.page.size
  const end = start + operationLogDialog.value.page.size
  
  operationLogDialog.value.total = filteredLogs.length
  operationLogDialog.value.list = filteredLogs.slice(start, end)
}

// 搜索操作记录
function searchOperationLog() {
  operationLogDialog.value.page.current = 1
  loadOperationLog()
}

// 重置操作记录过滤器
function resetOperationLogFilter() {
  operationLogDialog.value.filter.type = ''
  operationLogDialog.value.filter.dateRange = []
  operationLogDialog.value.page.current = 1
  loadOperationLog()
}

// 查看操作详情
function viewOperationDetail(log: OperationLog) {
  operationDetailDialog.value.data = { ...log }
  operationDetailDialog.value.title = `${getActionText(log.action)} - ${log.description}`
  operationDetailDialog.value.visible = true
}

// 格式化日期时间
function formatDateTime(timestamp: string): string {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取操作类型文本
function getActionText(action: string): string {
  const actionMap: Record<string, string> = {
    'create': '创建',
    'edit': '编辑',
    'publish': '发布',
    'cancel': '作废',
    'delete': '删除'
  }
  return actionMap[action] || action
}

// 获取操作类型标签颜色
function getActionTagType(action: string): string {
  const typeMap: Record<string, string> = {
    'create': 'success',
    'edit': 'warning',
    'publish': 'primary',
    'cancel': 'danger',
    'delete': 'danger'
  }
  return typeMap[action] || 'info'
}

// 获取状态标签颜色
function getStatusTagType(status: string): string {
  const typeMap: Record<string, string> = {
    '草稿': 'info',
    '发布': 'success',
    '作废': 'danger'
  }
  return typeMap[status] || 'info'
}

// 记录操作日志
function recordOperation(couponId: string, action: string, description: string, changes?: any[], remark?: string) {
  const log: OperationLog = {
    id: Date.now().toString(),
    couponId,
    timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
    operator: '当前用户', // 实际应该从用户状态获取
    action,
    description,
    ip: '192.168.1.100', // 实际应该从请求中获取
    changes,
    remark
  }
  
  if (!operationLogsData.value[couponId]) {
    operationLogsData.value[couponId] = []
  }
  operationLogsData.value[couponId].unshift(log)
}

function onSitesChange(val: string[]) {
  if (val.includes('all')) {
    dialog.value.form.sites = ['all']
  }
}

// 分类选项数据（来源于商品管理→分类管理）
const categoryOptions = ref([
  { value: 1, label: '服装服饰', children: [
    { value: 11, label: '男装', children: [] },
    { value: 12, label: '女装', children: [] }
  ] },
  { value: 2, label: '电子产品', children: [] },
  { value: 3, label: '书籍杂志', children: [] },
  { value: 4, label: '家居用品', children: [] },
  { value: 5, label: '游戏动漫', children: [] },
  { value: 6, label: '美妆个护', children: [] }
])

// 品牌选项数据
const brandOptions = ref([
  { value: 1, label: 'BANDAI' },
  { value: 2, label: 'TAKARA' },
  { value: 3, label: 'SEGA' },
  { value: 4, label: 'Nintendo' },
  { value: 5, label: 'Sony' },
  { value: 6, label: 'Apple' },
  { value: 7, label: 'Samsung' },
  { value: 8, label: 'Uniqlo' },
  { value: 9, label: 'Zara' },
  { value: 10, label: 'Nike' }
])

// 商品选项数据
const productOptions = ref([
  { id: 1, code: 'JAA001', name: 'JAA商品A', mainImage: 'https://dummyimage.com/30x30/409eff/fff&text=A' },
  { id: 2, code: 'JAA002', name: 'JAA商品B', mainImage: 'https://dummyimage.com/30x30/67c23a/fff&text=B' },
  { id: 3, code: 'JAA003', name: 'JAA商品C', mainImage: 'https://dummyimage.com/30x30/e6a23c/fff&text=C' },
  { id: 4, code: 'ML123', name: '煤炉商品A', mainImage: 'https://dummyimage.com/30x30/409eff/fff&text=ML' },
  { id: 5, code: 'YH456', name: '雅虎商品B', mainImage: 'https://dummyimage.com/30x30/67c23a/fff&text=YH' },
  { id: 6, code: 'XZ789', name: '闲置商品C', mainImage: 'https://dummyimage.com/30x30/e6a23c/fff&text=XZ' }
])

const productLoading = ref(false)
const loading = ref(false)

// 搜索商品方法
function searchProducts(query: string) {
  if (query !== '') {
    productLoading.value = true
    // 模拟搜索延迟
    setTimeout(() => {
      productOptions.value = [
        { id: 1, code: 'JAA001', name: 'JAA商品A', mainImage: 'https://dummyimage.com/30x30/409eff/fff&text=A' },
        { id: 2, code: 'JAA002', name: 'JAA商品B', mainImage: 'https://dummyimage.com/30x30/67c23a/fff&text=B' },
        { id: 3, code: 'JAA003', name: 'JAA商品C', mainImage: 'https://dummyimage.com/30x30/e6a23c/fff&text=C' },
        { id: 4, code: 'ML123', name: '煤炉商品A', mainImage: 'https://dummyimage.com/30x30/409eff/fff&text=ML' },
        { id: 5, code: 'YH456', name: '雅虎商品B', mainImage: 'https://dummyimage.com/30x30/67c23a/fff&text=YH' },
        { id: 6, code: 'XZ789', name: '闲置商品C', mainImage: 'https://dummyimage.com/30x30/e6a23c/fff&text=XZ' }
      ].filter(item => 
        item.name.toLowerCase().includes(query.toLowerCase()) ||
        item.code.toLowerCase().includes(query.toLowerCase())
      )
      productLoading.value = false
    }, 200)
  } else {
    productOptions.value = []
  }
}

function onScopeChange(val: string[]) {
  if (val.includes('all')) {
    dialog.value.form.scope = ['all']
    // 清空其他选择
    dialog.value.form.selectedCategories = []
    dialog.value.form.selectedBrands = []
    dialog.value.form.selectedProducts = []
  } else {
    // 当取消选择某个类型时，清空对应的选择数据
    if (!val.includes('category')) {
      dialog.value.form.selectedCategories = []
    }
    if (!val.includes('brand')) {
      dialog.value.form.selectedBrands = []
    }
    if (!val.includes('product')) {
      dialog.value.form.selectedProducts = []
    }
  }
}

// 搜索方法
function handleSearch() {
  page.value.current = 1
  // 搜索逻辑已在computed中实现，这里只需要重置页码
}

// 重置搜索
function resetSearch() {
  search.value = ''
  searchForm.value = {
    type: '',
    status: '',
    validType: '',
    sites: '',
    scope: '',

    dateRange: []
  }
  advancedSearchForm.value = {
    minAmount: null,
    maxAmount: null,
    grantType: '',
    quantityType: '',
    minClaimed: null,
    maxClaimed: null,
    customerTags: []
  }
  page.value.current = 1
}

// 切换高级搜索显示
function toggleAdvancedSearch() {
  showAdvancedSearch.value = !showAdvancedSearch.value
}


</script>

<style scoped>
.coupon-manage {
  padding: 16px;
}

/* 表单样式 */
.coupon-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 8px;
}

.coupon-form::-webkit-scrollbar {
  width: 6px;
}

.coupon-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.coupon-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.coupon-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 32px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #409eff;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-title .el-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 18px;
}

/* 表单项间距 */
.coupon-form .el-form-item {
  margin-bottom: 32px;
}

.coupon-form .el-form-item:last-child {
  margin-bottom: 0;
}

/* 同一行内输入框间距 */
.coupon-form .el-col {
  padding-left: 12px;
  padding-right: 12px;
}

.coupon-form .el-col:first-child {
  padding-left: 0;
}

.coupon-form .el-col:last-child {
  padding-right: 0;
}

/* 表单分组间距 */
.form-section {
  margin-bottom: 40px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.form-section:last-child {
  margin-bottom: 0;
}

/* 分组标题间距 */
.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #409eff;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-title .el-icon {
  margin-right: 10px;
  color: #409eff;
  font-size: 18px;
}



/* 提示信息样式 */
.form-tip {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  color: #409eff;
  font-size: 12px;
}

.form-tip .el-icon {
  margin-right: 6px;
  font-size: 14px;
}

/* 对话框底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-section {
    padding: 16px;
  }
  
  .section-title {
    font-size: 15px;
  }
}

@media (max-width: 768px) {
  .coupon-form {
    max-height: 60vh;
  }
  
  .form-section {
    padding: 12px;
    margin-bottom: 24px;
  }
  
  .section-title {
    font-size: 14px;
  }
}
.table-actions {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

/* 富文本编辑器对齐样式 */
:deep(.ql-editor) {
  min-height: 150px;
}

:deep(.ql-container) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.ql-toolbar) {
  border: 1px solid #dcdfe6;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
}

:deep(.ql-container) {
  border-radius: 0 0 4px 4px;
}

/* 操作记录样式 */
.operation-log-content {
  padding: 0;
}

.log-filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-panel {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.advanced-search {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.operation-detail {
  padding: 16px;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.detail-item .label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  margin-right: 8px;
}

.changes-list {
  flex: 1;
}

.change-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.change-item .field-name {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.change-item .old-value {
  color: #f56c6c;
  text-decoration: line-through;
  margin-right: 8px;
}

.change-item .arrow {
  color: #909399;
  margin-right: 8px;
}

.change-item .new-value {
  color: #67c23a;
  font-weight: 500;
}
</style> 